package com.gears_software.sxdc.dccx.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.maps.model.LatLng;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.IZPOrderFinder;
import com.gears_software.sxdc.dccx.data.model.AddZPOrderModel;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.request.RZPOrderModel;
import com.gears_software.sxdc.dccx.ui.fragment.SpecialCarFragment;
import com.gears_software.sxdc.dccx.ui.fragment.SpecialCarFragment_;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;

import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by chezhenzhen on 2017/11/22.
 */

@EActivity(R.layout.activity_relpacecallcar)
public class RelpaceCallCarActivity extends AppCompatActivity {

    @App
    DCCXApplication app;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView txt_user_icon;
    @ViewById
    TextView txt_phone_icon;
    @ViewById
    TextView txt_contact_icon;
    @ViewById
    EditText edit_username;
    @ViewById
    EditText edit_phone;
    @Extra
    LatLng mStartPosition;
    @Extra
    LatLng mEndPosition;
    @Extra
    RZPOrderModel rzpOrderModel;
    @RestService
    IZPOrderFinder zpOrderFinder;
    Context context;

    @AfterViews
    void created() {
        context = this;
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));
        initIconFont();
    }

    private void initIconFont() {
        actionbar_title.setText("代人叫车");
        back_icon.setText(R.string.back_icon);
        back_icon.setTypeface(app.iconfont);
        right_icon.setVisibility(View.VISIBLE);
        right_icon.setText("确定");
        right_icon.setTextSize(16);
        txt_contact_icon.setTypeface(app.iconfont);
        txt_user_icon.setTypeface(app.iconfont);
        txt_phone_icon.setTypeface(app.iconfont);
    }

    @Click
    void txt_contact() {
        getPermission();
    }

    //获取通讯录权限
    private void getPermission() {
        //获取定位权限
        AndPermission.with(this)
                .requestCode(100)
                .permission(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE)
                .callback(listener)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(RelpaceCallCarActivity.this, rationale).
                                show();
                    }
                })
                .start();
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            if (requestCode == 100) {
                Uri uri = ContactsContract.Contacts.CONTENT_URI;
                Intent intent = new Intent(Intent.ACTION_PICK, uri);
                startActivityForResult(intent, 0);
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            if (requestCode == 100) {
                TastyToast.makeText(RelpaceCallCarActivity.this, "获取手机通讯录权限失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);

            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0) {
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);
                edit_username.setText(contacts[0]);
                if (contacts[1].indexOf(" ") != -1){
                    edit_phone.setText(contacts[1].replace(" ", ""));
                }else if (contacts[1].indexOf("-") != -1){
                    edit_phone.setText(contacts[1].replace("-", ""));
                }

                TastyToast.makeText(this, "姓名:" + contacts[0] + " " + "手机号:" + contacts[1], app.LONG, app.SUCCESS);
                Logger.d("姓名:" + contacts[0] + " " + "手机号:" + contacts[1]);
            }
        }
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    @Click
    void right_icon() {
        if (edit_username.getText().toString().trim().equals("")) {
            TastyToast.makeText(this, "请输入乘车人姓名", app.SHORT, app.WARNING);
        } else if (edit_phone.getText().toString().trim().equals("")) {
            TastyToast.makeText(this, "请输入乘车人手机号码", app.SHORT, app.WARNING);
        } else {
            if (rzpOrderModel != null) {
                rzpOrderModel.setPassengername(edit_username.getText().toString().trim());
                rzpOrderModel.setPassengerphone(edit_phone.getText().toString().trim());
                addZPOrder(rzpOrderModel);
            }
        }

    }

    @Background
    void addZPOrder(RZPOrderModel orderModel) {
        ResultModel<AddZPOrderModel> res = zpOrderFinder.addZCOrder(orderModel);
        showAddResult(res);
    }

    @UiThread
    void showAddResult(ResultModel<AddZPOrderModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    AddZPOrderModel zpOrderModel = res.getData();
                    if (zpOrderModel.getIsok() == 1) {
                        MainActivity.instance.specialCar.modifyState();
                        Intent intent = new Intent(this, WaitForJieJiaNewActivity_.class);
                        intent.putExtra("mStartPosition", mStartPosition);
                        intent.putExtra("mEndPosition", mEndPosition);
                        intent.putExtra("orderModelDetail", zpOrderModel.getOrder());
                        startActivity(intent);
                        this.finish();
                    } else if (zpOrderModel.getIsok() == 2) {
                        new MaterialDialog.Builder(this)
                                .title("提示")
                                .titleGravity(GravityEnum.CENTER)
                                .titleColorRes(R.color.colorFontGray)
                                .content("您有末支付的订单，请前往我的行程进行支付。")
                                .contentColorRes(R.color.colorFontGray)
                                .positiveText("确定")
                                .positiveColor(ContextCompat.getColor(this, R.color.colorFontBlue))
                                .buttonsGravity(GravityEnum.CENTER)
                                .show();
                    } else if (zpOrderModel.getIsok() == 3) {
                        new MaterialDialog.Builder(this)
                                .title("提示")
                                .titleGravity(GravityEnum.CENTER)
                                .titleColorRes(R.color.colorFontGray)
                                .content(zpOrderModel.getMsg())
                                .contentColorRes(R.color.colorFontGray)
                                .positiveText("确定")
                                .positiveColor(ContextCompat.getColor(this, R.color.colorFontBlue))
                                .buttonsGravity(GravityEnum.CENTER)
                                .show();
                    } else if (zpOrderModel.getIsok() == 4) {
                        new MaterialDialog.Builder(this)
                                .title("提示")
                                .titleGravity(GravityEnum.CENTER)
                                .titleColorRes(R.color.colorFontGray)
                                .content(zpOrderModel.getMsg())
                                .contentColorRes(R.color.colorFontGray)
                                .positiveText("确定")
                                .positiveColor(ContextCompat.getColor(this, R.color.colorFontBlue))
                                .buttonsGravity(GravityEnum.CENTER)
                                .show();
                    }
                }
            }
        }
    }
    @Click
    void back_icon(){
        this.finish();
    }
}
